#include "widgetrecord.h"
#include "ui_widget.h"
#include "RecordThread.h"
#include <QBuffer>

WidgetRecord::WidgetRecord(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_pRecordThread = NULL;
    m_iRecordTimer = 0;

    qsrand(0);
}

WidgetRecord::~WidgetRecord()
{
    delete ui;
}

void WidgetRecord::on_colorBtn_clicked()
{
    QString strSty = QString("background-color:rgb(%1,%2,%3)")
            .arg(getValueWithin(256)).arg(getValueWithin(256)).arg(getValueWithin(256));
    this->setStyleSheet(strSty);
}

void WidgetRecord::on_recordBtn_clicked()
{
    QPushButton *pBtn = qobject_cast<QPushButton*>(this->sender());
    QString strText = pBtn->text();
    if(strText == "Start")
    {
        m_pRecordThread = new RecordThread();
        m_pRecordThread->setWidgetSize(this->size());
        bool bOk = connect(this, SIGNAL(sigSendPixData(const QByteArray&)),
                            m_pRecordThread, SLOT(slotRcvData(const QByteArray&)));
        Q_ASSERT(bOk);

        m_pRecordThread->start();
        pBtn->setText("Stop");
        m_iRecordTimer = startTimer(50);

    }
    else
    {
        m_pRecordThread->stopThread();
        m_pRecordThread = NULL;
        m_iRecordTimer = 0;
        pBtn->setText("Start");
    }
}

int WidgetRecord::getValueWithin(const int &iMax)
{
    return qrand() / iMax;
}


#include <QLabel>
void WidgetRecord::timerEvent(QTimerEvent *event)
{
    QPixmap pix = this->grab(this->rect());

   // killTimer(m_iRecordTimer);

//    QLabel *pLabel = new QLabel;
//    pLabel->setPixmap(pix);
//    pLabel->show();

    QByteArray pixData;
    pixData.clear();

    QBuffer buffer(&pixData);
    bool bOk = pix.save(&buffer, "jpg");

    if(!pixData.isEmpty() && bOk)
    {
        emit sigSendPixData(pixData);
    }
}
